package edu.sctu.jarime.june.day20150617;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by user19 on 2015/6/17.
 */
public class KnowHTTPConnection {
    /**
     * Created by IntelliJ IDEA.
     * User: user
     * Date: 2015-6-18
     * Time: 13:34:10
     * 模拟Http访问的工具类
     */

        public static String getHttpContent(String url) throws Exception {
            return getHttpContent(url, "GB2312");
        }

        public static String getHttpContent(String url, String charSet) throws Exception{
            HttpURLConnection connection = null;
            String content = "";
                URL address_url = new URL(url);
                connection = (HttpURLConnection) address_url.openConnection();
//            connection.setRequestMethod("GET");
                //设置访问超时时间及读取网页流的超市时间,毫秒值
                System.setProperty("sun.net.client.defaultConnectTimeout","30000");
                System.setProperty("sun.net.client.defaultReadTimeout", "30000");

                //after JDK 1.5
//            connection.setConnectTimeout(10000);
//            connection.setReadTimeout(10000);
                //得到访问页面的返回值
                int response_code = connection.getResponseCode();
                if (response_code == HttpURLConnection.HTTP_OK) {
                    InputStream in = connection.getInputStream();
//                InputStreamReader reader = new InputStreamReader(in,charSet);
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in, charSet));
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        content+=line;
                    }
                    return content;
                }
                if(connection !=null){
                    connection.disconnect();
                }
            return "";
        }


    }

